/*Copyright ©2015 TommyLemon(https://github.com/TommyLemon)

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.*/

package soft.hb.activity;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.anthony.rvhelper.adapter.CommonAdapter;
import com.anthony.rvhelper.base.ViewHolder;

import java.util.ArrayList;
import java.util.List;

import soft.hb.R;
import soft.hb.model.Project;
import soft.hb.model.Task;
import soft.hb.model.User;
import soft.hb.model.Vehicle;
import soft.hb.util.Constant;
import soft.hb.util.HttpRequest;
import zuo.biao.library.base.BaseActivity;
import zuo.biao.library.interfaces.OnHttpResponseListener;
import zuo.biao.library.ui.AlertDialog;
import zuo.biao.library.ui.DatePickerWindow;
import zuo.biao.library.ui.WebViewActivity;
import zuo.biao.library.util.JSON;
import zuo.biao.library.util.Log;

/**
 * 非道路移动器械待办任务
 *
 * @author yuanweiwei
 */
public class ProjectDetailsActivity extends BaseActivity implements OnClickListener, OnHttpResponseListener, AlertDialog.OnDialogButtonClickListener {
    public static final String TAG = "ProjectDetailsActivity";


    private VehicleAdapter mAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.project_details_activity);
        intent = getIntent();

        //功能归类分区方法，必须调用<<<<<<<<<<
        initView();
        initData();
        initEvent();
        //功能归类分区方法，必须调用>>>>>>>>>>

    }

    /**
     * 获取启动IndexActivity的intent
     *
     * @param context
     * @return
     */
    public static Intent createIntent(Context context) {
        return new Intent(context, ProjectDetailsActivity.class);
    }


    @Override
    public Activity getActivity() {
        return this; //必须return this;
    }

    //UI显示区(操作UI，但不存在数据获取或处理代码，也不存在事件监听代码)<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    private RecyclerView recyclerView;

    private TextView tvName;
    private TextView tvType;
    private TextView tvOffice;
    private TextView tvStartDate;
    private TextView tvEndDate;
    private TextView tvManager;
    private TextView tvMobile;
    private TextView tvMechanicsunit;
    private TextView tvMechanicsmanager;
    private TextView tvMechanicsMobile;
    private TextView tvOilsource;
    private TextView tvOilsourceMobile;
    private TextView tvAddress;

    private Button btnSubmit;

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    @Override
    public void initView() {//必须调用
        recyclerView = findView(R.id.rv_vehicle);
        tvName = (TextView) findViewById(R.id.tv_project_name);
        tvAddress = (TextView) findViewById(R.id.tv_project_address);
        tvType =  (TextView) findViewById(R.id.tv_project_type);
        tvOffice  =  (TextView) findViewById(R.id.tv_project_office);
        tvStartDate    =  (TextView) findViewById(R.id.tv_startDate);
        tvEndDate     =  (TextView) findViewById(R.id.tv_endDate);
        tvManager     =  (TextView) findViewById(R.id.tv_manager);
        tvMobile       =  (TextView) findViewById(R.id.tv_mobile);
        tvMechanicsunit        =  (TextView) findViewById(R.id.tv_mechanicsmanager);
        tvMechanicsmanager        =  (TextView) findViewById(R.id.tv_mechanicsMobile);
        tvMechanicsMobile          =  (TextView) findViewById(R.id.tv_oilsource);
        tvOilsource           =  (TextView) findViewById(R.id.tv_oilsourceMobile);
        tvOilsourceMobile           =  (TextView) findViewById(R.id.tv_mechanicsunit);

        findView(R.id.btn_submit).setOnClickListener(this);


    }


    //UI显示区(操作UI，但不存在数据获取或处理代码，也不存在事件监听代码)>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>


    //Data数据区(存在数据获取或处理代码，但不存在事件监听代码)<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<




    @Override
    public void initData() {//必须调用
        mAdapter = new VehicleAdapter(this);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(mAdapter);

        String projectId = getIntent().getStringExtra("projectId");
        showProgressDialog(R.string.loading);
        HttpRequest.pendingTaskProject(projectId,0, new OnHttpResponseListener() {
            @Override
            public void onHttpResponse(int requestCode, String resultJson, Exception e) {
                JSONObject jsonObject = JSON.parseObject(resultJson);
                if(jsonObject.getBoolean("success")){
                    JSONObject data = jsonObject == null ? null : jsonObject.getJSONObject("data");
                    Project project = JSON.parseObject(data, Project.class);
                    String type = "";
                    if(project.getType() !=null && project.getType().equals("1")){
                        type = "建设";
                    }else if(project.getType() !=null && project.getType().equals("2")){
                        type = "拆迁";
                    }else if(project.getType() !=null && project.getType().equals("3")){
                        type = "市容园林";
                    }else if(project.getType() !=null && project.getType().equals("4")){
                        type = "交通运输";
                    }else if(project.getType() !=null && project.getType().equals("5")){
                        type = "水务";
                    }else if(project.getType() !=null && project.getType().equals("6")){
                        type = "其他";
                    }


                    tvName.setText(project.getName());
                    tvAddress.setText(project.getAddress());
                    tvType.setText(type);
                    tvOffice.setText(project.getOffice());
                    tvStartDate.setText(project.getStartDate());
                    tvEndDate.setText(project.getEndDate());
                    tvManager.setText(project.getManager());
                    tvMobile.setText(project.getMobile());
                    tvMechanicsunit.setText(project.getMechanicsunit());
                    tvMechanicsmanager.setText(project.getMechanicsmanager());
                    tvMechanicsMobile.setText(project.getMechanicsMobile());
                    tvOilsource.setText(project.getOilsource());
                    tvOilsourceMobile.setText(project.getOilsourceMobile());
                    Log.i("TAG", resultJson);
                    List<Vehicle> lsVehicle = project.getProjectVehicleList();
                    onDataReceived(lsVehicle);
                }else{
                    showShortToast(jsonObject.getString("msg"));
                }
                dismissProgressDialog();
            }
        });
    }

    //Data数据区(存在数据获取或处理代码，但不存在事件监听代码)>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>


    //Event事件区(只要存在事件监听代码就是)<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

    @Override
    public void initEvent() {//必须调用
    }


    //系统自带监听方法<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_submit:
                new AlertDialog(context, "提交任务", "确定提交完成任务？", true, 0, this).show();
                break;


        }
    }


    //类相关监听<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case 10001:

                showProgressDialog(R.string.loading);
                String projectId = getIntent().getStringExtra("projectId");
                HttpRequest.pendingTaskProject(projectId,0, new OnHttpResponseListener() {
                    @Override
                    public void onHttpResponse(int requestCode, String resultJson, Exception e) {
                        JSONObject jsonObject = JSON.parseObject(resultJson);
                        if(jsonObject.getBoolean("success")){
                            JSONObject data = jsonObject == null ? null : jsonObject.getJSONObject("data");
                            Project project = JSON.parseObject(data, Project.class);
                            List<Vehicle> lsVehicle = project.getProjectVehicleList();
                            mAdapter.clearData();
                            onDataReceived(lsVehicle);
                        }else{
                            showShortToast(jsonObject.getString("msg"));
                        }
                        dismissProgressDialog();
                    }
                });


                break;
        }

    }


    @Override
    public void finish() {
        super.finish();

    }

    @Override
    public void onHttpResponse(int requestCode, String resultJson, Exception e) {

    }


    //类相关监听>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

    //系统自带监听方法>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>


    //Event事件区(只要存在事件监听代码就是)>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

    /**
     * todo load topic images
     * @param "List<TeacherBean>"
     */
    private void onDataReceived(List<Vehicle> vList) {
        mAdapter.addDataAll(vList);
        mAdapter.notifyDataSetChanged();

    }

    @Override
    public void onDialogButtonClick(int requestCode, boolean isPositive) {
        if (! isPositive) {
            return;
        }

        switch (requestCode) {
            case 0:

                showProgressDialog(R.string.loading);

                String taskId = getIntent().getStringExtra("taskId");
                Task task = new Task();
                task.setId(taskId);
                HttpRequest.submitTask(task,0, new OnHttpResponseListener() {
                    @Override
                    public void onHttpResponse(int requestCode, String resultJson, Exception e) {
                        JSONObject jsonObject = JSON.parseObject(resultJson);
                        if(jsonObject.getBoolean("success")){
                            showShortToast("提交成功,请继续下一个任务！");

                            startActivity(PendingTaskActivity.createIntent(ProjectDetailsActivity.this));
                        }else{
                            showShortToast(jsonObject.getString("msg"));
                        }
                        dismissProgressDialog();
                    }
                });


                break;
            default:
                break;
        }
    }


    public class VehicleAdapter extends CommonAdapter<Vehicle> {
        public VehicleAdapter(Context context) {
            super(context, R.layout.project_item_view);
        }

        @Override
        protected void convert(ViewHolder holder, final Vehicle item, int position) {
            String type = "";
            if (item.getMechanicalType()!=null && item.getMechanicalType().equals("1")){
                type = "挖掘机";
            }else  if (item.getMechanicalType()!=null && item.getMechanicalType().equals("2")){
                type = "推土机";
            }else  if (item.getMechanicalType()!=null && item.getMechanicalType().equals("3")){
                type = "装载机";
            }else  if (item.getMechanicalType()!=null && item.getMechanicalType().equals("4")){
                type = "叉车";
            }else  if (item.getMechanicalType()!=null && item.getMechanicalType().equals("5")){
                type = "压路机";
            }else  if (item.getMechanicalType()!=null && item.getMechanicalType().equals("6")){
                type = "摊路机";
            }else  if (item.getMechanicalType()!=null && item.getMechanicalType().equals("7")){
                type = "平地机";
            }else  if (item.getMechanicalType()!=null && item.getMechanicalType().equals("8")){
                type = "柴油发电机组";
            }else  if (item.getMechanicalType()!=null && item.getMechanicalType().equals("9")){
                type = "其他";
            }


            holder.setText(R.id.tv_code,item.getCode());
            holder.setText(R.id.tv_voucherNo,item.getVoucherNo());
            holder.setText(R.id.tv_detectionTime,item.getDetectionTime());
            holder.setText(R.id.tv_KAvg,item.getKAvg());
            holder.setText(R.id.tv_mechanicalType,type);
            holder.setText(R.id.tv_brand,item.getBrand());
            holder.setText(R.id.tv_power,item.getPower());
            holder.setText(R.id.tv_entryTime,item.getEntryTime());
            holder.setText(R.id.tv_timeOfAppearance,item.getTimeOfAppearance());
            holder.setText(R.id.tv_machineOwner,item.getMachineOwner());
            holder.setText(R.id.tv_mobile,item.getMobile());
            holder.setText(R.id.tv_grade,item.getGrade());
            holder.setText(R.id.tv_parkedPlace,item.getParkedPlace());

            holder.itemView.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(ProjectDetailsActivity.this,ModifyActivity.class);
                    intent.putExtra("id",item.getVehicle().getId());
                    startActivityForResult(intent,10001);

                }
            });

        }
    }
}